import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/components/calendar_header.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/home/menstrual_mode.dart';
import 'package:share_fit/app/routes/home_routes.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'package:table_calendar/table_calendar.dart';

import 'logic.dart';

class CycleCalendarPage extends StatelessWidget {
  CycleCalendarPage({super.key});

  final logic = Get.put(CycleCalendarLogic());
  final state = Get.find<CycleCalendarLogic>().state;

  late PageController _pageController;

  late CalendarFormat _calendarFormat = CalendarFormat.month;
  final RangeSelectionMode _rangeSelectionMode = RangeSelectionMode.toggledOn;

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvoked: (didPop) => logic.onPopInvoked(didPop),
      child: Scaffold(
        appBar: AppBar(
          leading: BackBtnIcon(onTap: () => logic.goBack()),
          centerTitle: true,
          title: Text(LocaleKeys.widgets_cycle_calendar.ts, style: TextStyle(fontSize: 54.sp)),
          actions: [
            IconButton(
              icon: Image.asset('assets/images/home/cycle_calendar_setting.png', width: 54.w, height: 54.h),
              onPressed: () async {
                await Get.toNamed(HomeRoutes.cycleCalendarSettingPage);
                logic.update(['cycle_calendar_events']);
              },
            )
          ],
        ),
        body: Container(
          padding: EdgeInsets.symmetric(horizontal: 40.w),
          child: ListView(
            children: [
              SizedBox(height: 36.h),
              _buildCalendarContainer(),
              SizedBox(height: 96.h),
              // _buildSwitchContainer(),
              // SizedBox(height: 96.h),
            ],
          ),
        ),
      ),
    );
  }

  _buildCalendarContainer() {
    return GetBuilder<CycleCalendarLogic>(
      id: 'cycle_calendar_events',
      builder: (ctrl) => Column(
        children: [
          CalendarHeader(
            locale: Get.locale?.languageCode,
            focusedDay: ctrl.state.focusedDay,
            onLeftArrowTap: () => {
              _pageController.previousPage(
                duration: const Duration(milliseconds: 300),
                curve: Curves.easeOut,
              )
            },
            onRightArrowTap: () => {
              _pageController.nextPage(
                duration: const Duration(milliseconds: 300),
                curve: Curves.easeOut,
              )
            },
            onTodayButtonTap: () => {},
            onClearButtonTap: () => {},
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 50.h, horizontal: 50.w),
            decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
            child: Column(
              children: [
                SizedBox(
                  height: 1050.h,
                  child: TableCalendar<MenstrualEvent>(
                    calendarBuilders: CalendarBuilders<MenstrualEvent>(
                      markerBuilder: (context, day, events) {
                        if (events.isEmpty) return const SizedBox();
                        return Container(
                          width: 25.w,
                          height: 25.w,
                          decoration: BoxDecoration(shape: BoxShape.circle, color: Color(events[0].color)),
                        );
                      },
                    ),
                    locale: Get.locale?.languageCode,
                    firstDay: DateUtils.addMonthsToMonthDate(DateTime.now(), -1),
                    // lastDay: _.state.lastDay.isBefore(DateTime.now()) ? DateTime.now() : _.state.lastDay,
                    lastDay: ctrl.state.lastDay,
                    focusedDay: ctrl.state.focusedDay,
                    calendarFormat: _calendarFormat,
                    headerVisible: false,
                    shouldFillViewport: true,
                    daysOfWeekHeight: 40,
                    availableGestures: AvailableGestures.horizontalSwipe,
                    startingDayOfWeek: Get.locale?.languageCode == 'zh' ? StartingDayOfWeek.monday : StartingDayOfWeek.sunday,
                    selectedDayPredicate: (day) => isSameDay(ctrl.state.selectedDay, day),
                    rangeSelectionMode: _rangeSelectionMode,
                    // rangeStartDay: state.rangeStart,
                    // rangeEndDay: state.rangeEnd,
                    eventLoader: (day) => ctrl.getEventsForDay(day),
                    onPageChanged: (focusedDay) => ctrl.changeFocusDay(focusedDay),
                    onDaySelected: (selectedDay, focusedDay) => ctrl.onDaySelected(selectedDay, focusedDay),
                    // onRangeSelected: (start, end, focusedDay) => _.onRangeSelected(start, end, focusedDay),
                    onCalendarCreated: (controller) => _pageController = controller,
                    onFormatChanged: (format) => _calendarFormat = format,
                    calendarStyle: CalendarStyle(
                      outsideDaysVisible: false,
                      markersAlignment: Alignment.bottomCenter,
                      todayTextStyle: const TextStyle(color: Colors.black54),
                      todayDecoration: BoxDecoration(
                        color: Colors.white,
                        shape: BoxShape.circle,
                        border: Border.all(width: 1, color: Colors.red),
                      ),
                      selectedDecoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle),
                    ),
                  ),
                ),
                SizedBox(height: 70.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Container(
                          height: 30.h,
                          width: 30.w,
                          decoration: BoxDecoration(color: Colors.red, borderRadius: BorderRadius.circular(100.r)),
                        ),
                        SizedBox(width: 15.w),
                        Text(LocaleKeys.cycle_calendar_during_text.ts, style: TextStyle(fontSize: 36.sp)),
                      ],
                    ),
                    Row(
                      children: [
                        Container(
                          height: 30.h,
                          width: 30.w,
                          decoration: BoxDecoration(color: Colors.amberAccent, borderRadius: BorderRadius.circular(100.r)),
                        ),
                        SizedBox(width: 15.w),
                        Text(LocaleKeys.cycle_calendar_measurement_text.ts, style: TextStyle(fontSize: 36.sp)),
                      ],
                    ),
                    Row(
                      children: [
                        Container(
                          height: 30.h,
                          width: 30.w,
                          decoration: BoxDecoration(color: Colors.green, borderRadius: BorderRadius.circular(100.r)),
                        ),
                        SizedBox(width: 15.w),
                        Text(LocaleKeys.cycle_calendar_ovulation_text.ts, style: TextStyle(fontSize: 36.sp)),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _buildSwitchContainer() {
    return Container(
      height: 190.h,
      padding: EdgeInsets.only(left: 80.w, right: 50.w),
      decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Image.asset('assets/images/home/menstrual.png', width: 80.w, height: 80.h),
              SizedBox(width: 20.w),
              Text(LocaleKeys.cycle_calendar_starting_text.ts),
            ],
          ),
          // Transform.scale(
          //   scale: 0.7,
          //   child: GetBuilder<CycleCalendarLogic>(
          //     id: HomeConst.cycleCalendarIsMenstruating,
          //     builder: (_) => CupertinoSwitch(
          //       value: _.state.isMenstruating,
          //       activeColor: ColorConst.accentColor,
          //       // onChanged: (value) => _.state.selectedDay != null ? _.isMenstruating(value) : null,
          //     ),
          //   ),
          // ),
        ],
      ),
    );
  }
}
